package com.bite.book.interceptor;

import com.bite.book.constants.Constant;
import com.bite.book.model.Result;
import com.bite.book.model.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.module.ResolutionException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("校验用户是否登录");
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USER_KEY);
        if(userInfo == null){
            log.warn("用户未登录");
            response.setStatus(401);
//            response.setContentType("application/json;charset=utf-8");
//            Result result = Result.fail("用户未登录");
//            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            return false;
        }
        log.info("用户登录检验通过");
        return true;
    }

//
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("目标方法执行后执行");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("视图渲染完成后执行后执行");
//    }
}
